package com.adam.management.service.impl;

import com.adam.management.dto.SysMenuDTO;
import com.adam.management.model.UserDTO;
import com.adam.management.entity.SysMenu;
import com.adam.management.mapper.SysMenuMapper;
import com.adam.management.response.ResponseData;
import com.adam.management.service.SysMenuService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @projectName: adam-management-system
 * @description:
 * @author: Adam
 * @create: 2019-10-16 13:23
 **/

@Service
public class SysMenuServiceImpl implements SysMenuService {

    private static Logger logger = LoggerFactory.getLogger(SysMenuServiceImpl.class);

    @Autowired
    private SysMenuMapper sysMenuMapper;


    /**
     * 获取有权限的菜单树
     * @param userDTO
     * @return
     */
    @Override
    public List<SysMenuDTO> getMenusWithPermission(UserDTO userDTO) {

        //TODO 后期此处还需处理为按角色查询
        List<SysMenuDTO> rootMenus = sysMenuMapper.selectLists();
        //logger.info(">>>>>>>>>>数据库中原始菜单记录=[{}]", JSON.toJSONString(rootMenus));

        //基本思路：先找出一级菜单 然后递归找到子菜单
        List<SysMenuDTO> menuList = new ArrayList<>();

        //所有一级菜单
        for (SysMenuDTO smd: rootMenus){
            if (smd.getMenuLevel()==1){
                menuList.add(smd);
            }
        }

        //为一级菜单赋子菜单
        for (SysMenuDTO menu: menuList){
            menu.setChildMenus(getChildMenus(menu.getId(),rootMenus));
        }
        return menuList;
    }

    /**
     * 生成没有子菜单的顺序菜单
     * @param userDTO
     * @return
     */
    @Override
    public List<SysMenuDTO> getMenusWithSorted(UserDTO userDTO) {
        List<SysMenuDTO> sortedMenus = new LinkedList<>();
        List<SysMenuDTO> formatMenus = this.getMenusWithPermission(null);
        this.generateSortedMenus(formatMenus,sortedMenus);
        return sortedMenus;
    }


    @Override
    @Transactional
    public ResponseData<Boolean> editMenuByPrimaryKey(SysMenuDTO sysMenuDTO) {
        try {
            int updateFlag = sysMenuMapper.updateSelectiveByPrimaryKey(sysMenuDTO);
            if (updateFlag==1){
                return ResponseData.success(true);
            }
            return ResponseData.fail("更新了0条记录");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.fail(e.getMessage());
        }
    }

    @Override
    public ResponseData<Boolean> addMenu(SysMenuDTO sysMenuDTO){
        SysMenu sysMenu = new SysMenu();
        try{
            BeanUtils.copyProperties(sysMenuDTO,sysMenu);
            int insertFlag = sysMenuMapper.insert(sysMenu);
            if (insertFlag ==1){
                return ResponseData.success(true);
            }
            return ResponseData.fail("插入0条记录");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.fail(e.getMessage(),false);
        }
    }

    @Override
    public ResponseData<Boolean> deleteMenu(List<String> ids) {
        try {
            int deleteFlag = sysMenuMapper.deleteBatchIds(ids);
            if (deleteFlag>0){
                return ResponseData.success(true);
            }
            return ResponseData.fail("删除失败");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.fail(e.getMessage());
        }
    }

    /**
     * 递归方法 生成嵌套的菜单树
     * @param id
     * @param rootMenus
     * @return
     */
    public List<SysMenuDTO> getChildMenus(Integer id, List<SysMenuDTO> rootMenus){
        // 子菜单
        List<SysMenuDTO> menuListChild = new ArrayList<>();
        //遍历所有父节点 子菜单的parentId与父菜单的id做对比
        for (SysMenuDTO menu: rootMenus) {
            if (menu.getParentId()==id){
                menuListChild.add(menu);
            }
        }
        //为子菜单 赋 子菜单
        for (SysMenuDTO menu: menuListChild){
            //当该子菜单不是父节点时会退出递归
            if (menu.getIsParent()==1){
                //递归
                menu.setChildMenus(getChildMenus(menu.getId(),rootMenus));
            }
        }
        return menuListChild;
    }


    /**
     * 递归生成顺序的无嵌套的菜单
     * @param sysMenuDTOS
     * @param sortedMenus 引用传递 持续为其add对象
     * @return
     */
    public void generateSortedMenus(List<SysMenuDTO> sysMenuDTOS,List<SysMenuDTO> sortedMenus){
         for (SysMenuDTO smDTO:sysMenuDTOS){
             SysMenuDTO sysMenuDTO = new SysMenuDTO();
               sysMenuDTO.setId(smDTO.getId());
               //为menuName以空格生成层级关系
               StringBuffer menuName = new StringBuffer(smDTO.getMenuName());
               //菜单级数-1为空格数
               Integer spaceNum = smDTO.getMenuLevel()-1;
               while (spaceNum>0){
                   menuName.insert(0," ");
                   spaceNum--;
               }

               sysMenuDTO.setMenuName(menuName.toString());
               sysMenuDTO.setMenuUrl(smDTO.getMenuUrl());
               sysMenuDTO.setParentId(smDTO.getParentId());
               sysMenuDTO.setIsParent(smDTO.getIsParent());
               sysMenuDTO.setMenuLevel(smDTO.getMenuLevel());
               sysMenuDTO.setMenuType(smDTO.getMenuType());
               sysMenuDTO.setMenuIcon(smDTO.getMenuIcon());
               sysMenuDTO.setMenuSort(smDTO.getMenuSort());
               sysMenuDTO.setRoleId(smDTO.getRoleId());
               sysMenuDTO.setRemark(smDTO.getRemark());
               sysMenuDTO.setStatus(smDTO.getStatus());
               sysMenuDTO.setGmtCreate(smDTO.getGmtCreate());
               sysMenuDTO.setGmtUpdate(smDTO.getGmtUpdate());
               sortedMenus.add(sysMenuDTO);
               if (smDTO.getChildMenus()!=null){
                   generateSortedMenus(smDTO.getChildMenus(),sortedMenus);
               }
         }
    }



}
